//
//  MallDetailViewController.m
//  CYWFrame
//
//  Created by Macx on 2017/8/31.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "MallDetailViewController.h"
#import <XRCarouselView.h>
#import <Masonry.h>
#import "Goods.h"
#import "GoodsComment.h"
#import <WebKit/WebKit.h>
#import "LCButton.h"
#import "MallCommentTableViewCell.h"
#import "MallCommitOrdersViewController.h"
#import "MallAllCommentViewController.h"
#import "NSString+Common.h"
#import "UIViewController+KNSemiModal.h"
#import "SpecViewController.h"
//#import "UIButton+zt_adjustImageAndTitle.h"
#import "MKJShoppingCartViewController.h"
#import "MallBuyTogetherTableViewCell.h"
#import "MallDetailBuyTogetherModel.h"
#import "MallBuyTogetherListViewController.h"
#import "ShopHomeViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>

@interface MallDetailViewController () <UIScrollViewDelegate, WKNavigationDelegate, UITableViewDelegate, UITableViewDataSource, UIWebViewDelegate, MallBuyTogetherCellDelegate>
@property (nonatomic, strong) NSMutableArray *commentArr;
@property (nonatomic, strong) NSString       *qq;
@property (nonatomic, strong) Goods *model;
@property (strong, nonatomic) LCButton *collectService;
@property (weak, nonatomic) IBOutlet UILabel *buyTogetherNum;
@property (weak, nonatomic) IBOutlet UIButton *buyTogetherMore;
@property (weak, nonatomic) IBOutlet UITableView *buyTogetherTableView;

@property (strong, nonatomic) NSMutableArray *buyTogetherInfoArr;


@end


@implementation MallDetailViewController{
    XRCarouselView  *_carouselView;
    UIScrollView    *_scrollView;
    UILabel         *_title;
    UILabel         *_money;
	UILabel         *_displayMoney;
    UILabel         *_CourierMoney;
    UILabel         *_soldNum;
    UIImageView     *_shopOwnerImg;
    UILabel         *_shopOwnerName;
    UILabel         *_address;
    UILabel         *_telephone;
    WKWebView       *_webView;
    LCButton        *_customerService;
    UIButton        *_shopCart;
    UIButton        *_settlement;
    UIButton        *_addCart;
    UILabel         *_commentNum;
    UIButton        *_commentBtn;
	UIButton        *_startBuyTogetherBtn;
    UITableView     *_tableView;
    MallCommentTableViewCell    *_cell;
    
    CGSize          _size1;
    CGSize          _size2;
    CGSize          _size3;
}

- (void)viewWillAppear:(BOOL)animated
{
	[self getBuyTogetherList];
}

- (void)viewDidLoad {
    [super viewDidLoad];
	if (self.isFromLive) {
		//self.view.frame = CGRectMake((SCREEN_WIDTH-self.viewSizeW)/2, (SCREEN_HEIGHT-self.viewSizeH)/2, self.viewSizeW, self.viewSizeH);
	}
	else{
		self.viewSizeW = self.view.frame.size.width;
		self.viewSizeH = self.view.frame.size.height;
	}
	

	NSLog(@"the viewW is %lf, viewH is %lf, x is %lf, y is %lf", self.view.size.width, self.view.size.height, self.view.origin.x,self.view.origin.y);
    // Do any additional setup after loading the view.
    
    [self createUI];
    
    [self GETGoods];
    
}


#pragma mark ==========构建UI==========
- (void)createUI {

    self.navigationItem.title = @"商品详情";
    
    self.view.backgroundColor = kWhiteColor;
    
    _size1 = [LZCTools textSizeWithText:@"字数" font:kUHSystemFontWithSize(12)];
    _size2 = [LZCTools textSizeWithText:@"字数" font:kUHSystemFontWithSize(11)];
    _size3 = [LZCTools textSizeWithText:@"字数" font:kUHSystemFontWithSize(10)];
	
    
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.viewSizeW, self.viewSizeH-49-64-10)];
    _scrollView.backgroundColor = kWhiteColor;
    [self.view addSubview:_scrollView];
    _scrollView.delegate = self;
	
    _carouselView = [[XRCarouselView alloc] initWithFrame:CGRectMake(0, 0, self.viewSizeW, self.viewSizeW)];
    [_scrollView addSubview:_carouselView];
    _carouselView.contentMode = UIViewContentModeScaleAspectFill;
    _carouselView.imageArray = @[IMAGE(@"img.jpg")];
    _carouselView.time = 2;
	
	if (self.isFromLive) {
		UIButton *returnToLive = [[UIButton alloc] initWithFrame:CGRectMake(self.viewSizeW-30, 30, 25, 25)];
		[returnToLive setBackgroundImage:IMAGE(@"live_close") forState:UIControlStateNormal];
		[returnToLive addTarget:self action:@selector(returnTolive:) forControlEvents:UIControlEventTouchUpInside];
		returnToLive.tag = 99;
		[self.view insertSubview:returnToLive atIndex:1];
		[self.view bringSubviewToFront:returnToLive];
	}
    
    _title = [[UILabel alloc] init];
    [_scrollView addSubview:_title];
    _title.font = kUHSystemFontWithSize(12);
    _title.numberOfLines = 2;
    _title.textColor = kGrayColor;
    _title.frame = CGRectMake(10, _carouselView.height+5, self.viewSizeW-20, _size1.height*2);
	
	_displayMoney = [[UILabel alloc] init];
	[_scrollView addSubview:_displayMoney];
	_displayMoney.font = kUHSystemFontWithSize(12);
	_displayMoney.textColor = kRedColor;
	_displayMoney.frame = CGRectMake(10, _title.y+_title.height, self.viewSizeW-20, _size1.height);
	
	_startBuyTogetherBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.viewSizeW-110, _displayMoney.y+5, 100, 30)];
	[_startBuyTogetherBtn setTitle:@"开团拼单" forState:UIControlStateNormal];
	[_startBuyTogetherBtn.titleLabel setFont:[UIFont systemFontOfSize:15]];
	[_startBuyTogetherBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
	[_startBuyTogetherBtn setBackgroundColor:kRedColor];
	_startBuyTogetherBtn.layer.cornerRadius = 5;
	_startBuyTogetherBtn.hidden = YES;
	[_startBuyTogetherBtn addTarget:self action:@selector(startBuyTogether) forControlEvents:UIControlEventTouchUpInside];
	[_scrollView addSubview:_startBuyTogetherBtn];
	
    _money = [[UILabel alloc] init];
    [_scrollView addSubview:_money];
    _money.font = kUHSystemFontWithSize(12);
    _money.textColor = kRedColor;
    _money.frame = CGRectMake(10, _displayMoney.y+_displayMoney.height+5, self.viewSizeW-20, _size1.height);
	
    _CourierMoney = [[UILabel alloc] init];
    [_scrollView addSubview:_CourierMoney];
    _CourierMoney.font = kUHSystemFontWithSize(10);
    _CourierMoney.textColor = kLightGrayColor;
    _CourierMoney.frame = CGRectMake(10, _money.height+_money.y+5, SW(3)-10, _size2.height);
    
    _soldNum = [[UILabel alloc] init];
    [_scrollView addSubview:_soldNum];
    _soldNum.font = kUHSystemFontWithSize(10);
    _soldNum.textColor = kLightGrayColor;
    _soldNum.frame = CGRectMake(SW(3), _CourierMoney.y, SW(3)-10, _size2.height);
	
	UIView *tagView = [[UIView alloc] initWithFrame:CGRectMake(0, _soldNum.height+_soldNum.y+10, self.viewSizeW, 45)];
	tagView.tag = 77;
	[_scrollView addSubview:tagView];
	
	UIView *line1 = nil;
	
	if ([self.isBuytogetherMode isEqualToString:@"1"]) {
		UIView *buyTogetherView = [[[NSBundle mainBundle] loadNibNamed:@"MallDetailBuyTogetherView" owner:self options:nil] lastObject];
		
		buyTogetherView.frame = CGRectMake(0, tagView.y+tagView.height+5, self.viewSizeW, 250);
		self.buyTogetherTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
		self.buyTogetherTableView.dataSource = self;
		self.buyTogetherTableView.delegate = self;
		[self.buyTogetherTableView registerNib:[UINib nibWithNibName:@"MallBuyTogetherTableViewCell" bundle:nil] forCellReuseIdentifier:@"buyTogetherCell"];
		[_scrollView addSubview:buyTogetherView];
		
		_startBuyTogetherBtn.hidden = NO;
		line1 = [self createLineFrame:CGRectMake(0, buyTogetherView.y+buyTogetherView.height, self.viewSizeW, 10)];
	}
	else {
		line1 = [self createLineFrame:CGRectMake(0, tagView.y+tagView.height+5, self.viewSizeW, 10)];
	}
	
	UIView *shopOwnerView = [[UIView alloc] initWithFrame:CGRectMake(0, line1.y+line1.height, self.viewSizeW, SW(10)+10)];
	shopOwnerView.backgroundColor = kWhiteColor;
	[_scrollView addSubview:shopOwnerView];
	
    _shopOwnerImg = [[UIImageView alloc] init];
    [shopOwnerView addSubview:_shopOwnerImg];
    _shopOwnerImg.frame = CGRectMake(10, 5, SW(10), SW(10));
    
    _shopOwnerName = [[UILabel alloc] init];
    [shopOwnerView addSubview:_shopOwnerName];
    _shopOwnerName.textColor = kGrayColor;
    _shopOwnerName.font = kUHSystemFontWithSize(11);
    _shopOwnerName.frame = CGRectMake(_shopOwnerImg.width+_shopOwnerImg.x+10, _shopOwnerImg.y, self.viewSizeW-_shopOwnerName.x-20, _shopOwnerImg.height);
	UIImageView *arror1 = [UIImageView imageViewWithImage:IMAGE(@"arrow_next_grey")];
	arror1.frame = CGRectMake(shopOwnerView.width-20, shopOwnerView.height/2-9, 9, 18);
	[shopOwnerView addSubview:arror1];
	[shopOwnerView addActionWithblock:^{
		ShopHomeViewController *vc = [[ShopHomeViewController alloc] init];
		vc.shopId = [NSString stringWithFormat:@"%ld", self.model.shop_id];
		[self.navigationController pushViewController:vc animated:YES];
	}];
    
    UIView *line2 = [self createLineFrame:CGRectMake(0, shopOwnerView.y+shopOwnerView.height+1, self.viewSizeW, 1)];
	
	UIView *addressView = [[UIView alloc] initWithFrame:CGRectMake(0, line2.y+line2.height, self.viewSizeW, SW(10)+10)];
	addressView.backgroundColor = kWhiteColor;
	[_scrollView addSubview:addressView];
    UIButton *addressImg = [UIButton buttonWithType:UIButtonTypeCustom];
    [addressView addSubview:addressImg];
    addressImg.frame = CGRectMake(10, addressView.height/2-_size2.height/2, _size2.height, _size2.height);
    [addressImg setImage:IMAGE(@"address_detail") forState:UIControlStateNormal];
    
    _address = [[UILabel alloc] init];
    [addressView addSubview:_address];
    _address.textColor = kGrayColor;
    _address.font = kUHSystemFontWithSize(11);
    _address.frame = CGRectMake(addressImg.x+addressImg.width+5, addressImg.y, self.viewSizeW-50, addressImg.height);
	UIImageView *arror2 = [UIImageView imageViewWithImage:IMAGE(@"arrow_next_grey")];
	arror2.frame = CGRectMake(addressView.width-20, addressView.height/2-9, 9, 18);
	[addressView addSubview:arror2];
	[addressView addActionWithblock:^{
		if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
			NSNumber *lat = [self.model.shop valueForKey:@"lat"];
			NSNumber *lng = [self.model.shop valueForKey:@"lng"];
			NSString *urlString = [[NSString stringWithFormat:@"iosamap://path?sourceApplication=applicationName&sid=BGVIS1&did=BGVIS2&dlat=%f&dlon=%f&dname=%@&dev=0&m=0&t=0",lat.floatValue, lng.floatValue, _address.text]
				stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
			
			[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString] options:@{} completionHandler:^(BOOL success) { NSLog(@"高德地图调用结束"); }];
		}
		else if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"http://maps.apple.com/"]]) {
			NSNumber *lat = [self.model.shop valueForKey:@"lat"];
			NSNumber *lng = [self.model.shop valueForKey:@"lng"];
			CLLocationCoordinate2D desCoordinate = CLLocationCoordinate2DMake(lat.doubleValue, lng.doubleValue);
			
			MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
			MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:desCoordinate addressDictionary:nil]];
			toLocation.name = _address.text;//可传入目标地点名称
			[MKMapItem openMapsWithItems:@[currentLocation, toLocation]
						   launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];
		}
	}];
    
    UIView *line3 = [self createLineFrame:CGRectMake(0, addressView.y+addressView.height+1, self.viewSizeW, 1)];
	
	UIView *telephoneView = [[UIView alloc] initWithFrame:CGRectMake(0, line3.y+line3.height+1, self.viewSizeW, SW(10)+10)];
	telephoneView.backgroundColor = kWhiteColor;
	[_scrollView addSubview:telephoneView];
    UIButton *teleImg = [UIButton buttonWithType:UIButtonTypeCustom];
    [telephoneView addSubview:teleImg];
    teleImg.frame = CGRectMake(10, telephoneView.height/2-_size2.height/2, _size2.height, _size2.height);
    [teleImg setImage:IMAGE(@"shop_phone") forState:UIControlStateNormal];
    
    _telephone = [[UILabel alloc] init];
    [telephoneView addSubview:_telephone];
    _telephone.textColor = kGrayColor;
    _telephone.font = kUHSystemFontWithSize(11);
    _telephone.frame = CGRectMake(teleImg.x+teleImg.width+5, teleImg.y, self.viewSizeW-50, teleImg.height);
	__weak typeof (self)weakSelf = self;
	[telephoneView addActionWithblock:^{
		NSMutableString *tstr=[[NSMutableString alloc] initWithFormat:@"tel:%@", [weakSelf.model.shop valueForKey:@"tel"]];
		NSLog(@"手机号======%@",tstr);
		[[UIApplication sharedApplication] openURL:[NSURL URLWithString:tstr] options:@{} completionHandler:nil];
	}];
	UIImageView *arror3 = [UIImageView imageViewWithImage:IMAGE(@"arrow_next_grey")];
	arror3.frame = CGRectMake(telephoneView.width-20, telephoneView.height/2-9, 9, 18);
	[telephoneView addSubview:arror3];
    
    UIView *line4 = [self createLineFrame:CGRectMake(0, line3.y+11+_shopOwnerImg.height, self.viewSizeW, 10)];
    
    _webView = [[WKWebView alloc] init];
    [_scrollView addSubview:_webView];
    _webView.frame = CGRectMake(0, line4.y+line4.height, self.viewSizeW, 0);
    _webView.navigationDelegate = self;
    _webView.userInteractionEnabled = NO;
    
    UIView *line5 = [self createLineFrame:CGRectMake(0, 0, self.viewSizeW, 10)];
    [line5 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_webView.mas_bottom).offset(0);
        make.left.mas_equalTo(_scrollView.mas_left).offset(0);
        make.size.mas_equalTo(CGSizeMake(self.viewSizeW, 10));
    }];
    
    _commentNum = [[UILabel alloc] init];
    [_scrollView addSubview:_commentNum];
    _commentNum.textColor = kGrayColor;
    _commentNum.font = kUHSystemFontWithSize(11);
    [_commentNum mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(line5.mas_bottom).offset(0);
        make.left.mas_equalTo(_scrollView.mas_left).offset(10);
        make.size.mas_equalTo(CGSizeMake(SW(2), 44));
    }];
    
    _commentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_scrollView addSubview:_commentBtn];
    _commentBtn.titleLabel.font = kUHSystemFontWithSize(11);
    [_commentBtn setTitleColor:kGrayColor forState:UIControlStateNormal];
    [_commentBtn setTitle:@"所有评论" forState:UIControlStateNormal];
    [_commentBtn addTarget:self action:@selector(allCommentClick:) forControlEvents:UIControlEventTouchUpInside];
    [_commentBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(line5.mas_bottom).offset(0);
        //        make.right.mas_equalTo(_scrollView.mas_right).offset(-10);
        make.left.mas_equalTo(_commentNum.mas_right).offset(SW(4));
        make.size.mas_equalTo(CGSizeMake(_size2.width*3, 44));
    }];
    
    UIView *line = [self createLineFrame:CGRectMake(0, 0, self.viewSizeW, 10)];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_commentNum.mas_bottom).offset(0);
        make.left.mas_equalTo(_scrollView.mas_left).offset(0);
        make.size.mas_equalTo(CGSizeMake(self.viewSizeW, 1));
    }];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStylePlain];
    //[_scrollView addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    //_tableView.scrollEnabled = NO;
    _tableView.tableFooterView = [[UIView alloc]init];
    [_tableView registerNib:[UINib nibWithNibName:@"MallCommentTableViewCell" bundle:nil] forCellReuseIdentifier:@"mall"];
	
	/*
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(line.mas_bottom).offset(0);
        make.left.mas_equalTo(_scrollView.mas_left).offset(0);
        make.size.mas_equalTo(CGSizeMake(self.viewSizeW, 500));
    }];
	 */
    
//    _tableView.estimatedRowHeight = 200;
//    _tableView.rowHeight = UITableViewAutomaticDimension;
	
	
	//下面这个64应该是对应navigationbar的高度，理论上应该不用减去，但字数证明如果不减去在有navigationBar的情况下的确会被往下挤导致看不见，而当从直播间里显示是则不需要减
    UIView *line6 = [[UIView alloc] initWithFrame:CGRectMake(0, self.viewSizeH-49-Height_NavBar-10, self.viewSizeW, 10)];
	
	if (self.isFromLive) {
		line6.frame = CGRectMake(0, self.viewSizeH-49-10, self.viewSizeW, 10);
	}
    [self.view addSubview:line6];
    line6.backgroundColor = UISeparatedColorRGB;
    
    /*
    _customerService = [[LCButton alloc] initWithFrame:CGRectMake(5, line6.y+10+5, 39, 39)];
    [self.view addSubview:_customerService];
    [_customerService setTitle:@"客服" forState:UIControlStateNormal];
    [_customerService setTitleColor:kGrayColor forState:UIControlStateNormal];
    [_customerService setImage:IMAGE(@"icon_shop_cs") forState:UIControlStateNormal];
    [_customerService addTarget:self action:@selector(lbBtnClick:) forControlEvents:UIControlEventTouchUpInside];
     */
	UIView *btnView = [[UIView alloc] initWithFrame:CGRectMake(0, self.viewSizeH-50-Height_NavBar, SCREEN_WIDTH, 50)];
	if (self.isFromLive) {
		btnView = [[UIView alloc] initWithFrame:CGRectMake(0, self.viewSizeH-50, SCREEN_WIDTH, 50)];
	}
	[self.view addSubview:btnView];
	
    _collectService = [[LCButton alloc] initWithFrame:CGRectMake(15, 10, 40, 30)];
	_collectService.backgroundColor = kWhiteColor;
    _collectService.titleLabel.font = kUHSystemFontWithSize(9);
    [_collectService addTarget:self action:@selector(collectBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [_collectService setTitle:@"收藏" forState:UIControlStateNormal];
    [_collectService setImage:IMAGE(@"icon_shop_collect") forState:UIControlStateNormal];
    [_collectService.imageView setSize:CGSizeMake(15, 15)];
    [_collectService setTitleColor:kGrayColor forState:UIControlStateNormal];
    [btnView addSubview:_collectService];
    
	
    _shopCart = [[LCButton alloc] initWithFrame:CGRectMake(_collectService.x+_collectService.width+18, 10, 40, 30)];
	_shopCart.backgroundColor = kWhiteColor;
    [btnView addSubview:_shopCart];
    [_shopCart setTitle:@"购物车" forState:UIControlStateNormal];
    _shopCart.titleLabel.font = kUHSystemFontWithSize(9);
    //_shopCart.titleLabel.adjustsFontSizeToFitWidth = YES;
    [_shopCart setImage:IMAGE(@"per_cart") forState:UIControlStateNormal];
   
    [_shopCart setTitleColor:UIMainColorRGB forState:UIControlStateNormal];
    [_shopCart addTarget:self action:@selector(shopBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    _addCart = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnView addSubview:_addCart];
    _addCart.frame = CGRectMake(_shopCart.x+_shopCart.width+10, 0, (self.viewSizeW-(_shopCart.x+_shopCart.width+10))/2, 50);
    _addCart.backgroundColor = RGB(189, 238, 234);
    _addCart.titleLabel.font = kUHSystemFontWithSize(12);
    [_addCart setTitleColor:UIMainColorRGB forState:UIControlStateNormal];
    [_addCart setTitle:@"加入购物车" forState:UIControlStateNormal];
    [_addCart addTarget:self action:@selector(addCartClick:) forControlEvents:UIControlEventTouchUpInside];
    
    _settlement = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnView addSubview:_settlement];
    _settlement.frame = CGRectMake(_addCart.x+_addCart.width, 0, self.viewSizeW-(_addCart.x+_addCart.width), 50);
    _settlement.backgroundColor = UIMainColorRGB;
    _settlement.titleLabel.font = kUHSystemFontWithSize(12);
    [_settlement setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [_settlement setTitle:@"立即购买" forState:UIControlStateNormal];
    [_settlement addTarget:self action:@selector(settlementClick:) forControlEvents:UIControlEventTouchUpInside];
    
}

- (UIView *)createLineFrame:(CGRect)frame {
    UIView *line = [[UIView alloc] init];
    [_scrollView addSubview:line];
    line.backgroundColor = UISeparatedColorRGB;
    line.frame = frame;
    return line;
}

#pragma mark ==========UITableView==========
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	if ([tableView isEqual:self.buyTogetherTableView]) {
		MallBuyTogetherTableViewCell *cellBuyTogether = [tableView dequeueReusableCellWithIdentifier:@"buyTogetherCell"];
		cellBuyTogether.model = self.buyTogetherInfoArr[indexPath.row];
		cellBuyTogether.delegate = self;
		cellBuyTogether.selectionStyle = UITableViewCellSelectionStyleNone;
		return cellBuyTogether;
	}
	else{
		_cell = [tableView dequeueReusableCellWithIdentifier:@"mall"];
		
		GoodsComment *model = self.commentArr[indexPath.row];
		_cell.model = model;
		
		return _cell;
	}
	
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	
	if ([tableView isEqual:self.buyTogetherTableView]) {
		return self.buyTogetherInfoArr.count;
	}
	else{
		return self.commentArr.count;
	}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	if ([tableView isEqual:self.buyTogetherTableView]) {
		return 70;
	}
	else{
		return [_cell cellHeight];
	}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
	if ([tableView isEqual:self.buyTogetherTableView]) {
		
	}
	else {
		[tableView deselectRowAtIndexPath:indexPath animated:YES];
		NSLog(@"点击tableView.cell = %ld", indexPath.row);
	}
	
}


#pragma mark ==========响应方法==========
- (void)GETGoods {
    // GET /malls/goods/{id} 获取商品详情 id *商品ID
//#define APIMallsGoods                  [APIMalls stringByAppendingString:@"/goods"]
    NSString *url = [NSString stringWithFormat:@"%@/%ld", APIMallsGoods, self.goodId];
    [[NetworkTool sharedTool] requestWithName:@"获取商品详情" URLString:url parameters:nil method:@"GET" callBack:^(id responseObject) {
        
        Goods *model = [[Goods alloc] init];
        [model setValuesForKeysWithDictionary:responseObject[@"data"]];
        
        _carouselView.imageArray = model.photo;
		UIButton *returnBtn = (UIButton *)[self.view viewWithTag:99];
		[returnBtn resignFirstResponder];
		[self.view bringSubviewToFront:returnBtn];
        _title.text = model.title;
        _money.text = [NSString stringWithFormat:@"￥%.2lf", (float)model.mall_price/100];
		
		_displayMoney.hidden = NO;
		_money.textColor = kGrayColor;
		CGSize lineSize = [LZCTools textSizeWithText:_money.text font:kUHSystemFontWithSize(13)];
		UIView *line = [[UIView alloc] initWithFrame:CGRectMake(_money.x, _money.y+8, lineSize.width, 1)];
		line.backgroundColor = kGrayColor;
		[_scrollView addSubview:line];
		if ([self.isBuytogetherMode isEqualToString:@"1"]){
			_displayMoney.text = [NSString stringWithFormat:@"￥%.2lf", (float)[model.ecbuy_price floatValue]/100];
		}
		else {
			_displayMoney.text = [NSString stringWithFormat:@"￥%.2lf", (float)model.price/100];
		}
		
        _CourierMoney.text = [NSString stringWithFormat:@"快递:%.2lf", [[model.shop valueForKey:@"express_fee"] floatValue]/100];
        _soldNum.text = [NSString stringWithFormat:@"月销量:%ld笔", model.monthly_sales_count];
        [_shopOwnerImg sd_setImageWithURL:[NSURL URLWithString:[model.shop valueForKey:@"photo"]] placeholderImage:IMAGE(@"placeHolder")];
        _shopOwnerName.text = [model.shop valueForKey:@"shop_name"];
        _address.text = [NSString stringWithFormat:@"地址:%@", [model.shop valueForKey:@"addr"]];
        _telephone.text = [NSString stringWithFormat:@"联系电话:%@", [model.shop valueForKey:@"tel"]];
        NSMutableString *content = [[NSMutableString alloc] initWithString:model.details];
        [self webviewContent:content];
        _commentNum.text = [NSString stringWithFormat:@"评论(%ld)", model.comments_count];
        self.qq = [model.shop valueForKey:@"qq"];
        if (model.collected == nil) {
            [_collectService setTitle:@"收藏" forState:UIControlStateNormal];
            [_collectService setImage:IMAGE(@"icon_shop_collect") forState:UIControlStateNormal];
            [_collectService setTitleColor:kGrayColor forState:UIControlStateNormal];
        }
        else
        {
            [_collectService setTitle:@"已收藏" forState:UIControlStateNormal];
            [_collectService setImage:IMAGE(@"icon_collect_ed") forState:UIControlStateNormal];
            [_collectService setTitleColor:UIMainColorRGB forState:UIControlStateNormal];
        }
		
		//中间的七天退款那几个标签
		UIView *tagView = [self.view viewWithTag:77];
		CGFloat btnX = 10.0;
		CGFloat btnY = 5.0;
		NSArray *a = model.tags_list;
		for (int i = 0; i < a.count; i++) {
			UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
			[tagView addSubview:btn];
			[btn setImage:IMAGE(@"shop_car_chose") forState:UIControlStateNormal];
			[btn setTitle:a[i] forState:UIControlStateNormal];
			[btn setTitleColor:kGrayColor forState:UIControlStateNormal];
			btn.titleLabel.font = kUHSystemFontWithSize(10);
			CGSize btnSize = [LZCTools textSizeWithText:btn.titleLabel.text font:kUHSystemFontWithSize(10)];
			
			btn.frame = CGRectMake(btnX, btnY, btnSize.width+5+btnSize.height, btnSize.height);
			
			if (btn.x+btn.width > SCREEN_WIDTH-10) {
				btn.x = 10;
				btn.y += btnSize.height+5;
			}
			
			btnX = 10+btn.x+btn.width;
			btnY = btn.y;
		}
		self.model = model;
        
        
        // GET /malls/goods/{id}/comments 获取商品的评论列表 id * 商品ID page 页码 per_page 每页显示数
        // POST /malls/goods/{id}/comments 发表商品的评论 id *商品ID body * 评论内容 pics 附加图片，多张以逗号隔开，最多3张
//#define APIMallsGoods                  [APIMalls stringByAppendingString:@"/goods"]
        
        NSDictionary *param = @{@"per_page":@"2", @"page":@"1"};
        NSString *url = [NSString stringWithFormat:@"%@/%ld/comments", APIMallsGoods, (long)self.goodId];
        
        [[NetworkTool sharedTool] requestWithName:@"获取商品评论列表" URLString:url parameters:param method:@"GET" callBack:^(id responseObject) {
            
            NSArray *arr = responseObject[@"data"];
            
            for (NSDictionary *dict in arr) {
                GoodsComment *comment = [[GoodsComment alloc] init];
                [comment setValuesForKeysWithDictionary:dict];
                [self.commentArr addObject:comment];
            }
//            [_tableView reloadData];
            dispatch_async(dispatch_get_main_queue(), ^{
                [_tableView reloadData];
            });
        }];
        
    }];
    
//    [_tableView reloadData];
    
}

- (void)webviewContent:(NSMutableString *)content {
    
    [content appendString:@"<html>"];
    [content appendString:@"<head>"];
    [content appendString:@"<meta charset=\"utf-8\">"];
    [content appendString:@"<meta id=\"viewport\" name=\"viewport\" content=\"width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=false\" />"];
    [content appendString:@"<meta name=\"apple-mobile-web-app-capable\" content=\"yes\" />"];
    [content appendString:@"<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black\" />"];
    [content appendString:@"<meta name=\"black\" name=\"apple-mobile-web-app-status-bar-style\" />"];
    [content appendString:@"<style>img{width:100%;}</style>"];
    [content appendString:@"<style>table{width:100%;}</style>"];
    [content appendString:@"<title>webview</title>"];
    [_webView loadHTMLString:content baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
    
}
// wkwebView 代理
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"3、WKWebView加载完成时调用");
	[webView evaluateJavaScript:@"document.body.offsetHeight" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
		//获取页面高度，并重置webview的frame
		CGFloat documentHeight = [result doubleValue];
		CGRect frame = webView.frame;
		frame.size.height = documentHeight + 20/*显示不全*/;
		webView.frame = frame;
		
		//        _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, [_cell cellHeight]*2 + webView.y+webView.height+55);
		[self.view addSubview:_tableView];
		_scrollView.frame = CGRectMake(0, 0, SCREEN_WIDTH, webView.y+webView.height+20+54);
		_tableView.tableHeaderView = _scrollView;
		UIButton *returnBtn = (UIButton *)[self.view viewWithTag:99];
		[returnBtn resignFirstResponder];
		[self.view bringSubviewToFront:returnBtn];
		//        _tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-50);
		[_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
			make.top.mas_offset(0);
			make.left.mas_offset(0);
			make.width.mas_equalTo(self.view.mas_width);
			//            make.bottom.mas_offset(-64);
			make.height.mas_offset(SCREEN_HEIGHT-Height_NavBar-49);
		}];
	}];
}

- (void)getBuyTogetherList
{
	NSDictionary *param = @{
							@"per_page":@"6",
							@"page":@"1",
							};
	NSString *url = [NSString stringWithFormat:@"%@/%ld/details-ecbuy", APIMalls, (long)self.goodId];
	
	[[NetworkTool sharedTool] requestWithName:@"获取拼单列表" URLString:url parameters:param method:@"GET" callBack:^(id responseObject) {
		
		NSArray *arr = responseObject[@"data"];
		[self.buyTogetherInfoArr removeAllObjects];
		for (NSDictionary *dict in arr) {
			
			MallDetailBuyTogetherModel *model = [[MallDetailBuyTogetherModel alloc] init];
			[model setValuesForKeysWithDictionary:dict];
			[self.buyTogetherInfoArr addObject:model];
		}
		self.buyTogetherNum.text = [NSString stringWithFormat:@"%ld人在拼单",self.buyTogetherInfoArr.count];
		dispatch_async(dispatch_get_main_queue(), ^{
			[self.buyTogetherTableView reloadData];
		});
	}];
}

//Button
- (void)collectBtnClick:(LCButton *)sender {
    NSLog(@"点击收藏");
    
    //    [self certStatus];
    NSDictionary *dict = GetUserDefaule(USERINFO);
    
    /*
    if (![dict[@"cert_status"] isEqualToString:@"1"]) {
        [LZCTools HUDMessage:@"您当前身份状态无法进行这类操作" delay:1.0f];
        return;
    }
     */
    
    NSDictionary *param = @{@"goods_id":[NSString stringWithFormat:@"%ld", self.goodId]};
    
    if ([_collectService.titleLabel.text isEqualToString:@"收藏"]) {
        [[NetworkTool sharedTool] requestWithName:@"添加收藏" URLString:APIMallCollect parameters:param method:@"PUT" callBack:^(id responseObject) {
            [_collectService setTitle:@"已收藏" forState:UIControlStateNormal];
            [_collectService setTitleColor:UIMainColorRGB forState:UIControlStateNormal];
            [_collectService setImage:IMAGE(@"icon_collect_ed") forState:UIControlStateNormal];
            
        }];
    }
    else {
        [[NetworkTool sharedTool] requestWithName:@"删除收藏" URLString:APIMallUncollect parameters:param method:@"PUT" callBack:^(id responseObject) {
            [_collectService setTitle:@"收藏" forState:UIControlStateNormal];
            [_collectService setImage:IMAGE(@"icon_shop_collect") forState:UIControlStateNormal];
            [_collectService setTitleColor:kGrayColor forState:UIControlStateNormal];
        }];
    }
    
    
}

- (void)shopBtnClick:(LCButton *)sender {
    NSLog(@"点击购物车");
    MKJShoppingCartViewController *shopCart = [[MKJShoppingCartViewController alloc] init];
    [self.navigationController pushViewController:shopCart animated:YES];
}

- (void)lbBtnClick:(LCButton *)sender {
    NSLog(@"点击客服");
    
    NSString *str = [NSString stringWithFormat:@"mqq://im/chat?chat_type=wpa&uin=%@&version=1&src_type=web", self.qq];
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
    NSURL *url = [NSURL URLWithString:str];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    webView.delegate = self;
    [webView loadRequest:request];
    [self.view addSubview:webView];
    
}
- (void)addCartClick:(UIButton *)sender {
    NSLog(@"点击加入购物车");
	SpecViewController *vc = [[SpecViewController alloc] initWithNibName:@"SpecViewController" bundle:nil];
	vc.model = self.model;
	vc.type = 0;
	vc.goodId = self.goodId;
	[self presentSemiViewController:vc];
	/*
    NSDictionary *param = @{@"goods_id":[NSString stringWithFormat:@"%ld", self.goodId]};
    [[NetworkTool sharedTool] requestWithName:@"加入购物车" URLString:APIMallsCarts parameters:param method:@"PUT" callBack:^(id responseObject) {
        
    }];
	 */
    
}
- (void)settlementClick:(UIButton *)sender {
    NSLog(@"点击立即购买");
	SpecViewController *vc = [[SpecViewController alloc] initWithNibName:@"SpecViewController" bundle:nil];
	vc.model = self.model;
	vc.type = 1;
	vc.goodId = self.goodId;
	vc.delegate = self;
	[self presentSemiViewController:vc];
	/*
    NSDictionary *itemdic = @{@"goods_id":[NSString stringWithFormat:@"%ld", self.goodId],
                              @"quantity":@"1"};
    NSArray *arr = @[itemdic];
    NSDictionary *param = @{@"items":arr};
    
    
    [[NetworkTool sharedTool] requestWithName:@"下单" URLString:APIMallsOrders parameters:param method:@"POST" callBack:^(id responseObject) {
        
        MallCommitOrdersViewController *commmitVC = [[MallCommitOrdersViewController alloc] init];
//        commmitVC.order = responseObject[@"data"][0];
        
        commmitVC.orderData = responseObject[@"data"];
        [self.navigationController pushViewController:commmitVC animated:YES];

    }];
	 */
}

- (void)allCommentClick:(UIButton *)sender {
    NSLog(@"点击所有评论");
    MallAllCommentViewController *allCommentVC = [[MallAllCommentViewController alloc] init];
    allCommentVC.goodId = self.goodId;
    [self.navigationController pushViewController:allCommentVC animated:YES];
}

- (void)returnTolive:(UIButton *)sender {
    //[self dismissViewControllerAnimated:YES completion:nil];
	NSLog(@"i was called");
	[self.parentViewController removeChild:self];
}

- (void)joinTogether:(UIButton *)button :(NSString *)ecbuyId :(NSString *)hostBuyUserId
{
	NSString *myUserId = GetUserDefaule(USERINFO)[@"user_id"];
	if ([hostBuyUserId isEqualToString:myUserId]) {
		UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您不能加入自己开启的拼单" preferredStyle:UIAlertControllerStyleAlert];
		[alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
		[self presentViewController:alert animated:YES completion:nil];
		return;
	}
	NSLog(@"点击加入拼单");
	SpecViewController *vc = [[SpecViewController alloc] initWithNibName:@"SpecViewController" bundle:nil];
	vc.model = self.model;
	vc.type = 3;
	vc.goodId = self.goodId;
	vc.delegate = self;
	vc.ecbuy_id = ecbuyId;
	[self presentSemiViewController:vc];
}

- (void)startBuyTogether
{
	NSString *userId = GetUserDefaule(USERINFO)[@"user_id"];
	for (NSString *pindanId in [self.buyTogetherInfoArr valueForKey:@"user_id"])
	{
		if ([userId isEqualToString:pindanId]) {
			UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您在该商品下已存在拼单记录，无法重复拼单" preferredStyle:UIAlertControllerStyleAlert];
			[alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
			[self presentViewController:alert animated:YES completion:nil];
			return;
		}
	}
	NSLog(@"点击开启拼单");
	SpecViewController *vc = [[SpecViewController alloc] initWithNibName:@"SpecViewController" bundle:nil];
	vc.model = self.model;
	vc.type = 2;
	vc.goodId = self.goodId;
	vc.delegate = self;
	[self presentSemiViewController:vc];
}
- (IBAction)CheckBuyTogetherList:(id)sender {
	MallBuyTogetherListViewController *listVC = [[MallBuyTogetherListViewController alloc] init];
	listVC.model = self.model;
	listVC.goodId = self.goodId;
	[self.navigationController pushViewController:listVC animated:YES];
}

// 懒加载
- (NSMutableArray *)commentArr {
    if (_commentArr == nil) {
        _commentArr = [[NSMutableArray alloc] init];
    }
    return _commentArr;
}

- (NSMutableArray *)buyTogetherInfoArr
{
	if (_buyTogetherInfoArr == nil) {
		_buyTogetherInfoArr = [[NSMutableArray alloc] init];
	}
	return _buyTogetherInfoArr;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
